<template>
    <view class="container" v-if="practiseDatail">
        <view class="practise_top_block">
            <view class="practise_type">
                <text class="practise_type_text" v-if="curQuestionData.questionType==1">单选题</text>
                <text class="practise_type_text" v-else-if="curQuestionData.questionType==2">多选题</text>
                <text class="practise_type_text" v-else>判断题</text>
            </view>
            <view class="practise_num">
                <text class="">{{curQuestionNum}}</text>
                <text class="">/</text>
                <text class="">{{practiseDatail.totalCount}}</text>
            </view>
        </view>
        <view class="practise_title">
            <rich-text-component :receiveData="articleJsonData" v-if="articleJsonData"></rich-text-component>
        </view>
        <view class="practise_answer_block">
            <view class="practise_answer_list">
              <view class="practise_answer_item" v-for="(item, index) in curQuestionData.answerContent" :key="index" :data-info="item" :data-index="index" @click.stop="radioChange">
                <view class="practise_answer_item_title">
                    <block v-if="!item.showState">
                        <text :class="['practise_answer_item_tag',item.selectState?'select_active':'']">{{item.prefix}}</text>
                        <text class="practise_answer_item_text">{{item.title}}</text>
                    </block>
                    <block v-else >
                        <view style="color: #fff;" :class="['practise_answer_item_tag',item.right==1?'right_active':'err_active']">
                            <image v-if="item.right==1" class="practise_answer_item_img" src="https://image1.sansancloud.com/xianhua/2020_3/16/17/57/58_211.jpg?x-oss-process=style/preview_120"></image>
                            <image v-else class="practise_answer_item_img" src="https://image1.sansancloud.com/xianhua/2020_3/16/17/57/58_130.jpg?x-oss-process=style/preview_120"></image>
                        </view>
                        <text style="background: #fff;padding: 0;" :class="['practise_answer_item_text',item.right==1?'right_active':'err_active']">{{item.title}}</text>
                    </block>
                </view>
                <!-- <radio :value="item.right" hidden="true"></radio> -->
              </view>
              <view class="sure_btn_block" @click="submitAnswerFun" v-if="curQuestionData.questionType==2&&!selectAnswerState">
                  <text class="sure_btn">确定</text>
              </view>
            </view>
        </view>
        <!-- 答案解析 -->
        <view class="answer_result_block" v-if="selectAnswerState">
            <text class="answer_result_title">答案解析</text>
            <view class="answer_result_list">
                <view class="answer_results_list_left">
                    <view class="true_answer_list" style="color: #00c356;">
                        正确答案：
                        <text class="true_answer_item">{{rightAnswerListStr}}</text>
                    </view>
                    <view class="user_answer_list" :style="'color: '+(!rightState?'#ff4c2d':'#00c356')">
                        你的答案：
                        <text class="true_answer_item">{{selectAnswerNumStr}}</text>
                    </view>
                </view>
                <view class="user_answer_result">
                    <text style="color: #00c356;" v-if="rightState">回答正确</text>
                    <text style="color: #ff4c2d;" v-else>回答错误</text>
                </view>
            </view>
        </view>
        <!-- 题目解析 -->
        <view class="question_explain_block" v-if="selectAnswerState">
            <text class="answer_result_title">题目解析</text>
            <text class="answer_result_text">
                {{curQuestionData.tinyExplain}}
            </text>
            <view class="difficulty_grad">
                <text>难度星级</text>
                <view class="grad_list">
                    <image v-for="(item,grad) in curQuestionData.difficultyGrad" :key="grad" class="grad_icon" src="https://image1.sansancloud.com/naifen/2019_5/31/17/7/11_803.jpg?x-oss-process=style/preview_120"></image>
                </view>
            </view>
        </view>
        <view class="bottom_padding"></view>
        <!-- 底部按钮信息 -->
        <view class="practise_bottom_block">
            <view class="practise_bottom_left">
                <view class="practise_count_item">
                    <image class="practise_count_item_icon right_icon" src="https://image1.sansancloud.com/xianhua/2020_3/16/17/57/58_211.jpg?x-oss-process=style/preview_120"></image>
                    <text style="color: #00c356;">{{practiseDatail.rightCount}}</text>
                </view>
                <view class="practise_count_item">
                    <image class="practise_count_item_icon error_icon" src="https://image1.sansancloud.com/xianhua/2020_3/16/17/57/58_130.jpg?x-oss-process=style/preview_120"></image>
                    <text style="color: #ff4c2d;">{{practiseDatail.errorCount}}</text>
                </view>
            </view>
            <view class="practise_next_question" v-if="selectAnswerState" @click="nextQuestionFun">
                <!-- <image class="practise_next_question_icon" src="https://image1.sansancloud.com/xianhua/2020_3/18/12/1/29_388.jpg?x-oss-process=style/preview_120"></image> -->
                <text v-if="practiseDatail.totalCount>curQuestionNum&&nextQuestionData.nextQuestion">下一题</text>
                <text v-else>完成练习</text>
            </view>
        </view>
    </view>
</template>

<script>
import { socketFun } from "../../wxcomponents/public/json2Form";
export default {
  data() {
    return {
      practiseDatail:null,
      curQuestionData:null,
      secondColor:'',
      defaultColor:'',
      setting:null,
      params:{},
      curQuestionNum:1,//当前题目序号
      articleJsonData:'',
      selectAnswerNum:[],//用户选择答案列表
      selectAnswerNumStr:'',//用户选择答案列表
      selectAnswerState:false,
      rightAnswerList:[],//正确答案列表
      rightAnswerListStr:'',//正确答案列表
      rightState:false,
      nextQuestionData:null,
      reqStartPractiseUrl:'/wx_start_user_course_practise.html',
      reqfGetErrPractiseUrl:'/wx_get_user_course_practise_record_question.html',
      answerList:[{"prefix":"A","title":"正确","right":1},{"prefix":"B","title":"错误","right":0}]
    };
  },
  props: {},

  /*onload*/
  onLoad: function (options) {
    let that=this;
    console.warn("======onLoad:options======", options, getApp().globalData.setting);
    that.params=options;
    that.getPractiseData(options);
  },
  onReady: function () {
    
  },
  onShow: function () {
    let that=this;
	that.setData({
        setting:getApp().globalData.setting,
        defaultColor:getApp().globalData.setting.platformSetting.defaultColor,
        secondColor:getApp().globalData.setting.platformSetting.secondColor,
       })
  },
  /* 分享 app.js862行*/
  onShareAppMessage: function () {
    console.log(getApp().globalData.miniIndexPage);
    return getApp().globalData.shareForFx2(getApp().globalData.miniIndexPage);
  },
  onPullDownRefresh: function () {
    // let that = this; // 下拉刷新的时候首先判断存不存在tab
    // console.log("下拉");
    // that.articleJsonData=null
    // that.getPractiseData(that.params);
    // wx.stopPullDownRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('===onReachBottom====');
    let that = this
  },
  onPageScroll: function (object) {
      let that=this;
  },
  methods: {
    radioChange:function(e){
        console.log("==radioChange==",e);
        let that=this;
        let index=e.currentTarget.dataset.index;
        let curQuestionData=that.curQuestionData;
        let selectAnswerNumLength=0;
        let sameCount=0
        if(that.selectAnswerState){//已答题
            return
        }
        if(curQuestionData.questionType==2){
            selectAnswerNumLength=that.selectAnswerNum.length//多选题（可选多个答案）
            for(let i=0;i<that.selectAnswerNum.length;i++){//查重
                if(that.selectAnswerNum[i]==index){
                    sameCount++
                }
            }
        }
        if(sameCount==0){//已选答案列表 
            that.selectAnswerNum.splice(selectAnswerNumLength,1,index);
        }
        if(curQuestionData.questionType==2){//多选答案的选择效果
            if(curQuestionData.answerContent[index].selectState){
                curQuestionData.answerContent[index].selectState=false
                for(let i=0;i<that.selectAnswerNum.length;i++){//删除已选答案
                    if(that.selectAnswerNum[i]==index){
                        that.selectAnswerNum.splice(i,1);
                    }
                }
            }else{
                curQuestionData.answerContent[index].selectState=true
            }
            that.setData({
                curQuestionData:curQuestionData,
            })
        }else{//单选和判断
            that.sureAnswerFun(that.selectAnswerNum)
        }
        console.log("that.selectAnswerNum",that.selectAnswerNum,selectAnswerNumLength,curQuestionData)
    },
    submitAnswerFun:function(){
        let that=this;
        if(that.selectAnswerNum.length>=2){
           that.selectAnswerState=true;//已选答案
           that.sureAnswerFun(that.selectAnswerNum)
        }else{
            wx.showToast({
              title: '两个以上的答案!',
              image: '/wxcomponents/images/icons/tip.png',
              duration: 1000
            });
            return;
        }
    },
    sureAnswerFun:function(data){
        console.log("==sureAnswerFun==",data);
        let that=this;
        let errState=false;
        let curQuestionData=that.curQuestionData;
        let practiseDatail=that.practiseDatail
        for(let i=0;i<curQuestionData.answerContent.length;i++){
            curQuestionData.answerContent[i].showState=false;
            if(curQuestionData.answerContent[i].right==1){
                curQuestionData.answerContent[i].showState=true;
                that.rightAnswerList.splice(that.rightAnswerList.length,1,i)//正确答案列表展示出来
            }
        }
        console.log("rightAnswerList",that.rightAnswerList)
        for(let j=0;j<that.rightAnswerList.length;j++){
            errState=data.indexOf(that.rightAnswerList[j])
            for(let k=0;k<data.length;k++){
                if(that.rightAnswerList[j]!=data[k]){
                    curQuestionData.answerContent[data[k]].showState=true;
                }else{
                }
            }
        }
        console.log("==errState==",errState)
        // if(errState==-1){
        //     that.rightState=false
        //     practiseDatail.errorCount++
        // }else{
        //     that.rightState=true
        //     practiseDatail.rightCount++
            
        // }
        if(curQuestionData.questionType!=2){//单选和判断类型下只能点击一次
            that.selectAnswerState=true;//已选答案
        }
        //答案字符串化
        let selectAnswerNum=JSON.parse(JSON.stringify(that.selectAnswerNum.sort()))
        let rightAnswerList=JSON.parse(JSON.stringify(that.rightAnswerList))
        let answerData='';
        for(let i=0;i<selectAnswerNum.length;i++){
            selectAnswerNum[i]=that.curQuestionData.answerContent[selectAnswerNum[i]].prefix
        }
        for(let i=0;i<rightAnswerList.length;i++){
            rightAnswerList[i]=that.curQuestionData.answerContent[rightAnswerList[i]].prefix
        }
        if(curQuestionData.questionType!=3){
            answerData=selectAnswerNum.join(',')
        }else{
            answerData=that.curQuestionData.answerContent[that.selectAnswerNum[0]].right
        }
        that.setData({
            curQuestionData:curQuestionData,
            selectAnswerNumStr:selectAnswerNum.join(','),
            rightAnswerListStr:rightAnswerList.join(','),
            practiseDatail:practiseDatail
        })
        that.answerPractiseData(answerData)
    },
    /* 回答问题 */
    answerPractiseData: function (answer) {
      let that = this
      let param=Object.assign({},{},{
          recordId:that.practiseDatail.id,
          questionId:that.curQuestionData.id,
          answer:answer||'',
      })
      let customIndex = getApp().globalData.AddClientUrl("/wx_answer_user_course_practise.html", param)
      getApp().globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log(res.data)
          let data=res.data.relateObj
          let practiseDatail=that.practiseDatail
          if (!data) {
              wx.showToast({
                title: '回答失败!',
                image: '/wxcomponents/images/icons/tip.png',
                duration: 1000
              });
              return;
          } else {
            if(data.preQuestion.answerRight){
                that.rightState=true
            }else{
                that.rightState=false
            }
            practiseDatail.errorCount=data.errorCount
            practiseDatail.rightCount=data.rightCount
            that.setData({
                nextQuestionData:data,
                practiseDatail:practiseDatail
            })
          }
          wx.hideLoading()
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          getApp().globalData.loadFail()
        }
      })
    },
    nextQuestionFun:function(){
        let that=this;
        getApp().globalData.showToastLoading('loading', true)
        if(that.practiseDatail.totalCount<=that.curQuestionNum){
            wx.navigateBack({
              delta: 1
            });
        }else{
            that.articleJsonData=null
            that.practiseDatail=null
            that.curQuestionData=null
            setTimeout(function(){
                that.selectAnswerNum=[];
                that.selectAnswerNumStr='';
                that.selectAnswerState=false;
                that.rightAnswerList=[];
                that.rightAnswerListStr='';
                that.rightState=false;
                that.upDataFun(that.nextQuestionData)
            },200)
        }
    },
    /* 获取数据 */
    getPractiseData: function (params) {
      let that = this;
      let reqUrl='';
      if(params.practiseId){
          reqUrl=that.reqStartPractiseUrl
      }else{
          reqUrl=that.reqfGetErrPractiseUrl
      }
      let customIndex = getApp().globalData.AddClientUrl(reqUrl, params)
      getApp().globalData.showToastLoading('loading', true)
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading()
          console.log(res.data)
          let data=res.data.relateObj
          that.upDataFun(data)
          wx.hideLoading()
        },
        fail: function (res) {
          console.log("fail")
          wx.hideLoading()
          getApp().globalData.loadFail()
        }
      })
    },
    upDataFun:function(data){
        console.log("===upDataFun===",data)
        let that=this;
        if (!data ) {
            wx.showToast({
              title: '获取数据失败!',
              image: '/wxcomponents/images/icons/tip.png',
              duration: 1000
            });
          that.setData({ practiseDatail: {} })
        } else {
          if(data.nextQuestion.answerContent){
              data.nextQuestion.answerContent=JSON.parse(data.nextQuestion.answerContent)
              for(let i=0;i<data.nextQuestion.answerContent.length;i++){
                  data.nextQuestion.answerContent[i].showState=false;
                  data.nextQuestion.answerContent[i].selectState=false;
              }
          }
          if(data.nextQuestion.questionType==3){
              if(data.nextQuestion.booleanAnswer){
                  that.answerList[0].right=1
                  that.answerList[1].right=0
              }else{
                  that.answerList[0].right=0
                  that.answerList[1].right=1
              }
              data.nextQuestion.answerContent=that.answerList
              for(let i=0;i<data.nextQuestion.answerContent.length;i++){
                  data.nextQuestion.answerContent[i].showState=false;
                  data.nextQuestion.answerContent[i].selectState=false;
              }
          }
          if(data.questionIds){
              data.questionIds=data.questionIds.split(',')
              for(let i=0;i<data.questionIds.length;i++){
                  if(data.questionIds[i]==data.nextQuestion.id){
                      console.log("curQuestionNum",i)
                      that.setData({curQuestionNum:i+1})
                  }
              }
          }
          that.setData({
              practiseDatail:data,
              curQuestionData:data.nextQuestion,
          })
          if(data.nextQuestion.content){
              that.setData({
                articleJsonData: {jsonData:{content:data.nextQuestion.content}}
              });
          }
          console.log('====data.nextQuestion====', data,data.nextQuestion);
        }
        that.nextQuestionData=null;
        wx.hideLoading()
    },
    /* 组件事件集合 */
    tolinkUrl: function (e) {
      console.warn("=======e=======", e);
      let linkUrl = e.currentTarget?e.currentTarget.dataset.url:e;
      getApp().globalData.linkEvent(linkUrl);
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>